home *** CD-ROM | disk | FTP | other *** search
-
- #include "array.h"
-
- #define GROWTH_RATE 2
-
- /* Creates an Array and returns it */
-
- Array array_alloc(unsigned int aSize)
- {
- Array retVal;
-
- retVal = (Array) malloc(sizeof(struct _array));
-
- retVal->used = 0;
- retVal->size = aSize;
-
- retVal->data = (void **) calloc(aSize,sizeof(void *));
-
- return retVal;
- }
-
- /* Frees and array, not the items in it */
-
- void array_free(Array anArray)
- {
- if(anArray)
- {
- if(anArray->data) free(anArray->data);
-
- free(anArray);
-
- anArray = 0;
- }
- }
-
- /* Frees the items, not the array */
-
- void array_freeItems(Array anArray)
- {
- if(anArray)
- {
- if(anArray->used)
- {
- int i;
-
- for(i=0; i<anArray->used ;i++)
- {
- if((anArray->data)[i])
- {
- free((anArray->data)[i]);
- (anArray->data)[i] = 0;
- }
- }
- }
- }
- }
-
- /* returns the current size of an Array */
-
- int array_count(Array anArray)
- {
- int retVal;
-
- if(anArray) retVal = anArray->used;
- else retVal = -1;
-
- return retVal;
- }
-
-
- /* Sets the capacity of the array */
-
- void array_setCapacity(Array anArray,unsigned int aSize)
- {
- if(anArray && (aSize > anArray->size))
- {
- anArray->size = aSize;
- anArray->data = (void **) realloc(anArray->data,aSize*sizeof(void *));
- }
- }
-
- /* Adds an item to the end of the array */
-
- void array_addItem(Array anArray,void *anItem)
- {
- if(anArray) array_addItemAt(anArray,anItem,anArray->used);
- }
-
- /* Inserts an item into the array */
-
- void array_addItemAt(Array anArray,void *anItem,unsigned int index)
- {
- int i;
-
- if(anArray && ((index >= 0) && (index <= anArray->used)) && anItem)
- {
- anArray->used++;
-
- /* Make sure that we have space */
- if(anArray->used >= anArray->size)
- {
- array_setCapacity(anArray,anArray->used * GROWTH_RATE);
- }
-
- /* Move the current items up to make room */
- for(i=(anArray->used - 1); i > index ; i--)
- {
-
- anArray->data[i] = anArray->data[i-1];
-
- }
-
- /* Add the new item */
- anArray->data[i] = anItem;
- }
- }
-
- /* Returns an item from the array */
-
- void * array_itemAt(Array anArray,unsigned int index)
- {
- void *retVal = 0;
-
- if(anArray && ((index >= 0) && (index < anArray->used)))
- {
- retVal = anArray->data[index];
- }
-
- return retVal;
- }
-
- /* Removes an item from the array, and returns it */
-
- void * array_removeItemAt(Array anArray,unsigned int index)
- {
- void *retVal = 0;
- int i;
-
- if((index >= 0) && (index < anArray->used))
- {
- /* get the item to remove */
-
- retVal = anArray->data[index];
-
- /* Move the rest of the items down */
-
- for(i=index; i < anArray->used - 1;i++)
- {
- anArray->data[i] = anArray->data[i+1];
- }
-
- anArray->used--;
- }
-
- return retVal;
- }
-
-